package com.cloud.nio.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NewIoClient {

    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();

        socketChannel.connect(new InetSocketAddress("localhost",7001));

        String fileName = "U:\\messes\\SpringbootProject\\netty\\1.txt";

        FileChannel channel = new FileInputStream(fileName).getChannel();

        long size = channel.size();

        BigDecimal bigDecimal = new BigDecimal(size);
        BigDecimal divide = bigDecimal.divide(new BigDecimal(1024 * 8 * 1024)).setScale(0,BigDecimal.ROUND_CEILING);

        long startTime = System.currentTimeMillis();

        long count = 0l;

        while ((divide.compareTo(new BigDecimal(0))>0)) {
            // 在linux下一个transferTo 方法就可以完成传输
            // 在windows下 transferTo 只能发送8M大的文件，就需要分段传输文件，而且主要传输的位置
            count += channel.transferTo(0, channel.size(),socketChannel);
            divide = divide.subtract(BigDecimal.ONE);
        }

        System.out.println("发送总字节数："+count+",耗时："+(System.currentTimeMillis()-startTime));

        channel.close();

    }
}
